/**
 * @filename:SysUserRoleServiceImpl 2025-05-27
 * @project starhub-schema  V1.0
 */
package com.starhub.engine.sys.role.service.impl;

import com.starhub.common.sys.user.LoginUser;
import com.starhub.engine.generator.genid.IdGenerator;
import com.starhub.engine.sys.permission.dao.SysPermissionDao;
import com.starhub.engine.sys.permission.entity.SysPermission;
import com.starhub.engine.sys.role.dao.SysRolePermissionDao;
import com.starhub.engine.sys.role.entity.SysRolePermission;
import com.starhub.engine.sys.role.entity.SysUserRole;
import com.starhub.engine.sys.role.dao.SysUserRoleDao;
import com.starhub.engine.sys.role.request.SysUserRoleBsRequest;
import com.starhub.engine.sys.role.service.SysUserRoleService;
import com.starhub.utils.Util;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**   
 * @Description:(用户角色关联表设置服务实现)
 *
 * @version: V1.0
 * @author: luosw
 * 
 */
@Service
public class SysUserRoleServiceImpl implements SysUserRoleService {

    @Autowired
    private SysUserRoleDao userRoleDao;

    @Autowired
    private SysRolePermissionDao rolePermissionDao;

    @Autowired
    private SysPermissionDao permissionDao;

    /**
    * 新增
    * @param user
    * @param request
    * @return
    */
    public List<String> add(LoginUser user, SysUserRoleBsRequest request){

        List<String> addRoles = new ArrayList<>();
        List<String> roles = request.getRoles();
        List<String> users = request.getUsers();
        if(CollectionUtils.isNotEmpty(roles) && CollectionUtils.isNotEmpty(users)){
            SysUserRole record = new SysUserRole();
            List<SysUserRole> rolePermissionList = userRoleDao.selectByPrimaryKeySelective(record);
            List<String> existRoles = new ArrayList<>();
            if(CollectionUtils.isNotEmpty(rolePermissionList)) {
                for(SysUserRole sysUserRole:rolePermissionList){
                    String roleId = Util.null2String(sysUserRole.getRoleId());
                    String userId = Util.null2String(sysUserRole.getUserId());
                    existRoles.add(roleId+"_"+userId);
                }
            }
            for(String role : roles){
                for(String userStr :users){
                    String id = role+"_"+userStr;
                    if(!existRoles.contains(id)){
                        addRoles.add(id+"_"+"0");
                        Long uuid = IdGenerator.generateId();
                        Long roleId = Util.getLongValue(role);
                        Long userId = Util.getLongValue(userStr);
                        SysUserRole sysUserRole = new SysUserRole(uuid,userId,roleId);
                        userRoleDao.insertSelective(sysUserRole);
                    }else{
                        addRoles.add(id+"_"+"1");
                    }
                }
            }
        }
        return addRoles;


    }

    /**
    * 更新
    * @param user
    * @param userRole
    * @return
    */
    public SysUserRole update(LoginUser user, SysUserRole userRole){
        //不允许更新的属性设置为null
        userRoleDao.updateByPrimaryKeySelective(userRole);
        return userRole;
    }

    /**
    * 基本信息获取
    * @param user
    * @param id
    * @return
    */
    public SysUserRole getInfo(LoginUser user, Long id){

        SysUserRole userRole = userRoleDao.selectByPrimaryKey(id);
        return userRole;
    }

    /**
    * (批量)删除，同时支持单条或者批量,此方法为逻辑删除
    * @param user
    * @param ids
    */
    public void deleteByType(LoginUser user, String ids,int deleteType){

        //数组转换
        List<Long> idList = Arrays.stream(ids.split(","))
            .map((id) -> Long.parseLong(id))
            .collect(Collectors.toList());
            //删除状态，目前只有1的逻辑
        userRoleDao.deleteSysUserRoleByType(idList, deleteType);
    }

    /**
    * 根据id删除，此方法为真实删除
    * @param user
    * @param ids
    */
    public void deleteRecord(LoginUser user, String ids){

        //数组转换
        List<Long> idList = Arrays.stream(ids.split(","))
            .map((id) -> Long.parseLong(id))
            .collect(Collectors.toList());
        userRoleDao.deleteSysUserRoleRecord(idList);
    }

    /**
    * 列表查询
    * @param user
    * @param params
    */
    public List<SysUserRole> getList(LoginUser user,  Map<String , Object>  params){

        List<SysUserRole> userRoleList =  new ArrayList<SysUserRole>();
            //TODO
        int pageSize = 10;
        int current = 1;
        SysUserRole record = new SysUserRole();
        userRoleList = userRoleDao.selectByPrimaryKeySelective(record);
        return userRoleList;
    }

    @Override
    public Set<SysPermission> getPermissionCodes(Long userId) {

        Set<SysPermission> sysPermissions = new HashSet<>();
        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(userId);
        List<SysUserRole> userRoleList = userRoleDao.selectByPrimaryKeySelective(userRole);
        if(CollectionUtils.isNotEmpty(userRoleList)){
            List<Long> roleIds = userRoleList.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
            List<SysRolePermission> rolePermissionList = rolePermissionDao.selectByRoleIds(roleIds);
            if(CollectionUtils.isNotEmpty(rolePermissionList)){
                List<Long> permissionIds = rolePermissionList.stream().map(SysRolePermission::getPermissionId).collect(Collectors.toList());
                List<SysPermission> sysRolePermissions = permissionDao.selectByIds(permissionIds);
                if(CollectionUtils.isNotEmpty(rolePermissionList)){
                    sysPermissions = sysRolePermissions.stream().collect(Collectors.toSet());
                }
            }
        }
        return sysPermissions;
    }
}